/*IWA assignment 1 - core.js
 *Maximilian Einoeder
 *Mark Mensing
*/

//Vars
var debugXML = "<GeoIP><ReturnCode>1</ReturnCode><IP>68.1.143.227</IP><ReturnCodeDetails>Success</ReturnCodeDetails>";
debugXML += "<CountryName>United States</CountryName><CountryCode>USA</CountryCode></GeoIP>";

/*Insert the IP of the user in the textfield*/
function insertClientIp() {
    //Get the ip address via jsonip
    $.getJSON("http://jsonip.appspot.com?callback=?",
        function(data){
            //Set the ip in the textbox
            $("#inputIp").val(data.ip);
        });
}


$(document).ready(function() {
    //Form event handler
    $("#formIp").submit(function(event) {
        //Avoid the default action of the form
        event.preventDefault();
    
        //Get values from the page
        var $form = $( this ),
        term = $("input#inputIp").val(),
        target = $form.attr( 'action' );
   
        var xmlRequest = $.ajax({
            type: "GET",
            url: target,
            data: {ip : term},
            dataType: "html"            
        });
    
        //Wait for the response
        xmlRequest.done(function() {
            //Parse the xml
            var xml = xmlRequest.responseText,
            xmlDoc = $.parseXML( xml ),
            $xml = $( xmlDoc ),
            $country = $xml.find( "countryname" );
        
            //Show the country on the map and display a marker
            $("div#divMap").gMap({
                address: $country.text(), 
                zoom: 3,
                markers:[
                {
                    address: $country.text(),
                    html: term + " is in this country: " + $country.text()
                }
                ]
            });
        });
    
        xmlRequest.error(function() {
            alert("Something went wrong!");
        });
    });
});
